<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <FullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>部门信息</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <PageForm
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
              @handleEvent="pageHandleEvent"
            >
              <template v-slot:form-deptName>
                <el-input
                  v-model="formInfo.data.deptName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  :placeholder="'请选择部门'"
                >
                  <template #append>
                    <el-icon @click="checkDeptName"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </PageForm>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>选择产品</p>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <NewPageFilter
              v-model:query="filterInfo.query"
              :filter-btn="filterInfo.btn"
            >
              <template v-slot:filter-addData>
                <el-button
                  :disabled="!formInfo.data.tsSystemCode"
                  @click="addData"
                  >添加设备</el-button
                >
              </template>
              <template v-slot:filter-removeData>
                <el-button :disabled="!canRemoveAsset" @click="removeData()"
                  >删除设备</el-button
                >
              </template>
            </NewPageFilter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :tab-index="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isRowClickSelect="true"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
              </PageTable>
            </div>
          </div>
        </div>
      </FullScreen>
    </div>
    <!-- 选择部门 -->
    <SelectDept
      v-if="useDeptInfo.visible"
      v-model:show-dialog="useDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="useDeptInfo.query"
      :save-empty="true"
      @callback="callbackUseDept"
    />
    <!-- 添加设备 -->
    <SelectDevice
      v-if="selectDeviceObj.visible"
      v-model:show-dialog="selectDeviceObj.visible"
      :query="selectDeviceObj.query"
      :api="selectDeviceObj.api"
      :check-box="true"
      :highlightRow="true"
      @callback="callBackDevice"
    />
  </div>
</template>

<script setup name="deptEquipModify">
import { postDeptDevice, tripartiteSystemDevice } from '@/api/cmPreMgt'
const SelectDevice = defineAsyncComponent(() => import('./selectDevice'))

const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title'])
const emits = defineEmits()

const formRefs = ref([])
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    tsSystemCode: 'LIS',
  },
  fieldList: [
    {
      label: '使用部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '对接系统',
      value: 'tsSystemCode',
      type: 'select-model',
      code: 'client_id',
      required: true,
      event: 'tsSystemChange',
    },
  ],
  rules: {
    deptName: [
      { required: true, message: '请选择使用部门', trigger: 'change' },
    ],
    tsSystemCode: [
      {
        required: true,
        message: '请选择对接系统',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '100px',
})
const useDeptInfo = ref({
  visible: false,
  query: {
    status: 1,
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  btn: [
    { type: 'slot', value: 'addData' },
    { type: 'slot', value: 'removeData' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '设备编码', value: 'tsCode' },
    { label: '设备名称', value: 'tsName' },
    { label: '设备型号', value: 'tsStandard' },
    { label: '厂家', value: 'tsFactory' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeData,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectDeviceObj = ref({
  visible: false,
  api: tripartiteSystemDevice,
  query: {
    idNotIn: '',
    tsSystemCode: '',
  },
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveAsset = computed(() => {
  return tableInfo.value.selections.length
})

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})

// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function pageHandleEvent(event, data) {
  if (event === 'tsSystemChange') {
    tableInfo.value.data = []
  }
}
function save() {
  //新增
  if (tableInfo.value.data && tableInfo.value.data.length === 0) {
    proxy.$message.warning('请添加设备！')
    return
  }
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const details = tableInfo.value.data
    if (!details.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加设备',
      })
      return
    }
    const arr = []
    details.forEach((item) => {
      arr.push({
        deptId: formInfo.value.data['deptId'],
        tsSystemCode: formInfo.value.data['tsSystemCode'],
        tsDeviceId: item.id,
      })
    })
    postDeptDevice(arr).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify')
      }
    })
  })
}
function checkDeptName() {
  useDeptInfo.value.visible = true
}
function callbackUseDept(data) {
  if (data && data.id) {
    formInfo.value.data.deptName = data.name
    formInfo.value.data.deptId = data.id
  } else {
    formInfo.value.data.deptName = ''
    formInfo.value.data.deptId = -2
  }
}
//选择设备
function addData() {
  selectDeviceObj.value.query.idNotIn = null
  selectDeviceObj.value.query.tsSystemCode = formInfo.value.data.tsSystemCode
  if (tableInfo.value.data.length) {
    selectDeviceObj.value.query.idNotIn = tableInfo.value.data
      .map((item) => item.id)
      .toString()
  }
  selectDeviceObj.value.visible = true
}
function callBackDevice(data) {
  tableInfo.value.data = data.concat(tableInfo.value.data)
}
//删除设备
function removeData(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
</script>

<style scoped lang="scss"></style>
